import { JsonController, Param, Body, Get, Post, Put } from 'routing-controllers';
import { EnterpriseEntity } from '../entity/enterprise.entity';
import { login, register, update, select } from '../service/enterprise.service';
import { sign } from '../utils/auth';
import { Code } from '../utils/code';
import { message } from '../utils/result';

@JsonController('/enterprise')
export class EnterpriseController {
  @Post('/login')
  async login(@Body() entity: EnterpriseEntity) {
    const result = await login(entity);
    if (result) {
      const token = sign({ id: result.id, username: result.username });
      return message(Code.SUCCESS, '登录成功', `Bearer ${token}`);
    }
    return message(Code.ERROR_LOGIN, '用户名或密码错误');
  }

  @Post('/register')
  async register(@Body() entity: EnterpriseEntity) {
    const index = await register(entity);
    if (index == 1) {
      return message(Code.SUCCESS, '注册成功');
    }
    return message(Code.ERROR_REGISTER, '注册失败');
  }

  @Put('/update/:id')
  async update(@Param('id') id: string, @Body() user: EnterpriseEntity) {
    const index = await update(id, user);
    if (index == 1) {
      return message(Code.SUCCESS, '更新成功');
    }
    return message(Code.ERROR_UPDATE, '更新失败');
  }

  @Get('/select/:id')
  async select(@Param('id') id: string) {
    const result = await select(id);
    if (result) {
      return message(Code.SUCCESS, '获取成功', result);
    }
    return message(Code.ERROR_SELECT, '获取失败');
  }
}
